var express = require('express')

var router = express.Router()
var User = require('../beans/users.js')
var userController = require('../controllers/users')
var jwt = require('jsonwebtoken')
/* GET users listing. */
router.get('/', function (req, res, next) {
	res.send('respond with a resource')
})
// 注册
// 查询用户名
router.post('/del', (req, res) => {
	userController.doRegister(req.body, (result) => {
		res.json(result)
	})
})
router.get('/list', (req, res) => {
	userController.dofinduser((result) => {
		res.json(result)
	})
})
// 用户登录
const Cookies = require('cookies')
const Result = require('../beans/result.js')
router.post('/login', function (req, res, next) {
	// 获取注册的用户名和密码

	const token = jwt.sign(
		// 加密数据
		{ username: req.body.username },
		// 密钥
		key1,
		// 有效期
		{ expiresIn: '1d' }
	)
	// const user = new User(req.body.username, req.body.password)
	const user = {
		username: req.body.username,
		password: req.body.password,
	}
	// res.json(user.usernanme)
	// 调用控制层执行登录
	console.log('用户登录', user)
	userController.doLogin(user, (result) => {
		// 登录成功时为客户端写入一个cookie: loginok=true
		if (!result.err) {
			// var cookies = new Cookies(req, res, {
			// 	keys: ['myblogkeys'],
			// })
			// cookies.set('loginok', 'true', {
			// 	signed: true,
			// })
			result.data = {
				token,
			}
			res.json(result)
		} else {
			res.json(result)
		}
	})
})
// 管理员登录
// token加密
const key = 'lxjj'
const key1 = 'dawang'
router.post('/administrators', function (req, res) {
	if (req.body.username === 'jinx' && req.body.password === 'aa12345') {
		const token = jwt.sign(
			// 加密数据
			{ username: req.body.username },
			// 密钥
			key,
			// 有效期
			{ expiresIn: '1d' }
		)
		res.json({
			code: 200,
			data: {
				username: req.body.username,
				token: token,
			},
			msg: '登录成功',
		})
	} else {
		res.json({
			code: 400,
			msg: '账号或密码错误，登陆失败',
		})
	}
})
//管理员token验证

router.get('/verify', function (req, res) {
	console.log('token', req.headers.token, key)
	try {
		const data = jwt.verify(req.headers.token, key)
		res.json({
			code: 200,
			msg: '验证成功',
		})
		// 校验成功
	} catch (err) {
		// 校验失败
		res.json({
			code: 400,
			err,
			msg: '验证失败',
		})
	}
})
// 用户token验证
router.get('/userverify', function (req, res) {
	try {
		const data = jwt.verify(req.headers.token, key1)
		res.json({
			code: 200,
			msg: '验证成功',
		})
		// 校验成功
	} catch (err) {
		// 校验失败
		res.json({
			code: 400,
			err,
			msg: '验证失败',
		})
	}
})
module.exports = router
